<?php
namespace app\pays;

use app\models\PayNoticeModel;
use app\models\RechargeManager;
/**
 * 银联支付开发，其他的开发不要在这里 2018-3-7 温宗敏
 */
class UnionPay  extends PayCommon
{
	//银联支付接口地址
	protected $url = 'https://qr-test2.chinaums.com/netpay-portal/webpay/pay.do?';
	
	/**
     * @根据相关的参数获取银联支付链接
	 * @return array 返回的数据
     */
	public function getpayurl($param,$money)
	{
		//判断是否启用了支付
		if ($param['isuse'] != "1"){
			$this->errormsg("支付开关未启用，请联系管理员");
		}
		if($money <= 0){
			$this->errormsg("支付金额必须大于0");
		}
		//定义支付类型
		$payType=$param['msgType'];
		if(strlen($payType)==0)
		{
			$this->errormsg("银联支付类型不能为空值");
		}
		$result=array();
		switch($payType)
		{
			case 'WXPay.jsPay':
				//银联微信支付
				$result=$this->UnionWeiXinMd5($param,$money);
				break;
			case 'trade.jsPay':
				//银联支付宝支付
				$result=$this->UnionTradeMd5($param,$money);
				break;
			case 'qmf.jspay':
				//银联全民付
				$result=$this->UnionQmfMd5($param,$money);
				break;
			case 'qmf.webPay':
				//银联无卡支付
				$result=$this->UnionWebPayMd5($param,$money);
				break;
			default:
				$this->errormsg('未找到银联支付类型');
				break;
		}
		$this->paylogs('用户进行了银联支付数据请求并成功返回链接');
		$this->paylogs($result['result']);
		return json_encode($result);
	}

	/**
     * @model 数据库操作对象
	 * @money 需要支付的金额
	 * @exetype 操作类型
     */
	public function ExecuteMethod($model,$money,$exetype)
	{
		switch($exetype)
		{
			case 'pay':
				//根据签约用户查找银联签约数据
				$result = $model->findunionmodel($_SESSION['pid']);
				if(count($result)==0){
					$this->errormsg('暂未开启银联支付，请申请');
				}
				return $this->getpayurl($result[0],$money);
				break;
			case 'query':
				$this->errormsg('暂未开通银联查询');
				break;
			case 'refund':
				$this->errormsg('暂未开通银联退款');
				break;
			default:
				$this->errormsg('未能识别银联操作类型，请联系管理员');
				break;
		}
	}

	public function UnionNotice()
	{
		if(count($_POST)==0){
			$this->paylogs('银联支付通知接口接收参数错误');
			exit('FAILED');
		}
		$mid = isset($_POST['mid']) ? $_POST['mid'] : '';//商户号
		$tid = isset($_POST['tid']) ? $_POST['tid'] : '';//终端号
		$merOrderId = isset($_POST['merOrderId']) ? $_POST['merOrderId'] : '';//商户订单号
		//创建通知类对象，可以调用方法
		$payResult=new PayNoticeModel();
		if($payResult->findunionresult($mid,$tid,$merOrderId)!='0'){
			exit('SUCCESS');
		}
		if($_POST['status']=='TRADE_SUCCESS'){
			//$fields=array('mid','tid','attachedData','bankInfo','billFunds','billFundsDesc','couponAmount','buyerPayAmount',
			//	'totalAmount','invoiceAmount','merOrderId','payTime','seqId','settleDate','status','targetOrderId','targetSys','notifyId','sign');
			//foreach ($fields as $field) {
			//	$result[$field]=$_POST[$field];
			//}
			$result=$_POST;
			ksort($result);
			$buff = $this->ToUrlParams($result);
			//获取本商户的key
			$key = $payResult->findunionkey($result['tid'],$result['mid']);
			if(strlen($key)==0){
				$this->paylogs('未找到银联支付用户的key');
				exit('FAILED');
			}
			$stringSignTemp = $buff.$key;//key为证书密钥
			$this->paylogs($stringSignTemp);
			$sign = strtoupper(md5($stringSignTemp));
			if($sign == $result['sign']){
				$this->paylogs('银联支付验证成功，开始保存到数据库');
				$fields=array('mid','tid','attachedData','bankInfo','billFunds','billFundsDesc','couponAmount','buyerPayAmount',
				'totalAmount','invoiceAmount','merOrderId','payTime','seqId','settleDate','status','targetOrderId','targetSys','notifyId','sign');
				foreach ($fields as $field) {
					$finalresult[$field]=$_POST[$field];
				}
				$payResult->recordunion($finalresult);
				$this->paylogs('银联支付通知结果是成功');
				$payinfo=json_decode($finalresult['attachedData'],true);
				//往卡上充值-银联支付并到芯算卡上充值 type==7是固定的，不要随意修改
				(new RechargeManager())->Invok($finalresult['sign'],$payinfo['type'],$payinfo['p'],$payinfo['c'],$payinfo['n'],$payinfo['o'],$payinfo['pid']);
				exit('SUCCESS');
			}
			else{
				$buff2 = '';
				foreach ($result as $k => $v){
					if($k != 'sign'){
						$buff2 .= $k . '=' . $v . '&';
					}
				}
				$this->paylogs($buff2);
				$this->paylogs('银联支付MD验证错误，返回的Sign:'.$result['sign'].'&&&代码验签结果：'.$sign);
				exit('FAILED');
			}
		}
		$this->paylogs('银联支付通知结果是失败');
		exit('FAILED');
	}
}